/**
 * Created by wtfssd on 2017/9/15.
 */

import React, {Component} from 'react'
import {StyleSheet, Text, View, Alert, SectionList, Image, TouchableOpacity} from 'react-native'
import {connect} from 'react-redux'
import {List, Picker} from 'antd-mobile'
import NavigationBar from 'react-native-navbar'
import {Actions} from 'react-native-router-flux'
import CommonStyle, {SCREEN, Color} from '../../assets/styles/index'
import Line from '../common/line'
import Counter from '../common/counter'
import MyIcon from '../common/myIcon'
import BottomBar from './bottomBar'
import {createForm} from 'rc-form';

class Page extends Component {
    constructor(props) {
        super(props);
        this.state = {
            refreshing: false,
        };
    }


    deleteProduct(item) {
        this.props.dispatch({
            type: 'cart/delete',
            payload: {...item, user_id: this.props.auth.profile.member_id}
        })
    }

    /*刷新*/
    fetchData(market) {


        if (!this.props.auth.isSignIn) return;
        let market_id = null;
        if (market) {
            market_id = market[0];
            console.log(1);
        } else if (this.market) {
            market_id = this.market[0];
            console.log(2);
        } else if (this.props.cart.selectMarket) {
            market_id = this.props.cart.selectMarket.id;
            console.log(3);
        }
        if (market_id) {
            this.props.dispatch({
                type: 'cart/changeSelectedMarket',
                payload: {market_id}
            })
        }
    }

    onSelectMarkets = (market) => {
        this.market = market;
        this.fetchData(this.market);
    };

    /*分组 item点击*/
    onPressItem = (props) => {
        Alert.alert(
            '删除该商品?',
            '',
            [
                {
                    text: '确定', onPress: () => {
                    this.deleteProduct({product_id: props.id});
                }
                },
                {
                    text: '取消', onPress: () => {

                }, style: 'cancel'
                },
            ],
            {cancelable: true}
        )
    };

    /*数据源主键 */
    keyExtractor = (item, index) => item.id;
    /*分组头*/
    renderSection = ({section: {title}}, index) => {
        return (

            <View style={Styles.section}>
                <MyIcon name="shop" color="#499DF5" size={20 / 375 * SCREEN.width}/>
                <View style={{
                    display: 'flex',
                    flex: 1,
                    flexDirection: 'row',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    paddingRight: 5
                }}>
                    <Text style={[
                        CommonStyle.text1,
                        {
                            marginLeft: 10 / 375 * SCREEN.width,
                            marginTop: -3 / 375 * SCREEN.width
                        }
                    ]}>{title}</Text>
                    <Text style={{color: '#999999'}}>长按删除</Text>
                </View>
            </View>
        )
    };


    onPlusCartProduct(item) {
        const {dispatch} = this.props;
        dispatch({
            type: 'cart/add',
            payload: {...item, count: 1, product_id: item.id}
        })
    }

    onMinusCartProduct(item) {
        const {auth, dispatch} = this.props;
        dispatch({
            type: 'cart/add',
            payload: {...item, count: -1, product_id: item.id}
        })
    }

    renderItem = ({item}, index) => {
        return (
            <TouchableOpacity onLongPress={this.onPressItem.bind(this, item)} activeOpacity={0.9}>
                <View style={Styles.product}>
                    <Image source={{uri: item.preview}} style={Styles.productIcon}/>
                    <View style={Styles.itemRightContent}>
                        <Text>{item.name}</Text>
                        <Text>{item.spec}</Text>
                        <View style={Styles.price}>
                            <Text style={[CommonStyle.priceText]}>¥{item.price}</Text>
                            <Counter count={item.pivot.count}
                                     onPlus={this.onPlusCartProduct.bind(this, item)}
                                     onMinus={this.onMinusCartProduct.bind(this, item)}/>
                        </View>
                    </View>
                </View>
            </TouchableOpacity>
        )
    };
    /*分组分割线*/
    renderSectionSeparatorComponent = (item, index) => {
        if (item.leadingItem) {
            return <Line height={10}/>
        }
        return <Line height={1}/>;
    };

    renderListFooterComponent = () => {
        return null;
    };

    render() {
        let title = this.props.title;
        if (this.props.cart.selectMarket) {
            title = this.props.title + `(${this.props.cart.selectMarket.name})`
        }
        return (
            <View style={Styles.container}>
                <NavigationBar tintColor={Color.primary}
                               statusBar={{style: 'light-content'}}
                               title={{title, tintColor: 'white'}}
                />
                {this.props.auth.isSignIn ? <View style={Styles.container}>

                        {/*//TODO:市场列表*/}
                        <List>
                            <Picker
                                title={'农贸市场'}
                                cols={1}
                                onChange={this.onSelectMarkets}
                                data={this.props.cart.marketList}
                            >
                                <List.Item arrow='horizontal'
                                >
                                    农贸市场
                                </List.Item>
                            </Picker>
                        </List>
                        <Line height={10} backgroundColor={'#F2F2F2'}/>
                        <SectionList sections={this.props.cart.list.map((item, index) => ({
                            key: item.store_id,
                            data: item.sub,
                            title: "轻生活"
                        }))}
                                     stickySectionHeadersEnabled={false}
                                     renderSectionHeader={this.renderSection}
                                     keyExtractor={this.keyExtractor}
                                     refreshing={this.props.cart.loading}
                                     onRefresh={this.fetchData.bind(this)}
                                     style={Styles.list}
                                     SectionSeparatorComponent={this.renderSectionSeparatorComponent}
                                     ItemSeparatorComponent={Line.bind(null, {height: 1})}
                                     renderItem={this.renderItem}
                                     ListFooterComponent={this.renderListFooterComponent}

                        />
                        <BottomBar count={this.props.cart.count} total={this.props.cart.total} type='shopCart'
                                   onSubmit={Actions.submitOrder}/></View> :
                    <View style={Styles.noData}>
                        <Text>暂未登录!!</Text>
                        <TouchableOpacity onPress={Actions.auth}>
                            <View style={Styles.loginBtn}>
                                <Text style={{color: 'white'}}>立即登录</Text>
                            </View>
                        </TouchableOpacity>
                    </View>}

            </View>
        )
    }
}

const Styles = StyleSheet.create({
    container: {
        display: 'flex',
        flex: 1,
    },
    list: {
        backgroundColor: '#F2F2F2',
        flex: 1,
        width: SCREEN.width
    },
    section: {
        display: 'flex',
        height: 29 / 375 * SCREEN.width,
        flexDirection: 'row',
        alignItems: 'center',
        paddingLeft: 10 / 375 * SCREEN.width,
        backgroundColor: 'white'
    },
    product: {
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'center',
        height: 93.6 / 375 * SCREEN.width,
        paddingLeft: 19.4 / 375 * SCREEN.width,
        backgroundColor: 'white'
    },
    productIcon: {
        height: 80.8 / 375 * SCREEN.width,
        width: 80.8 / 375 * SCREEN.width,
        borderRadius: 40.4 / 375 * SCREEN.width
    },
    itemRightContent: {
        display: 'flex',
        height: '100%',
        flex: 1,
        justifyContent: 'space-around',
        paddingLeft: 20 / 375 * SCREEN.width,
        paddingRight: 10 / 375 * SCREEN.width,
        paddingHorizontal: 10 / 375 * SCREEN.width
    },
    price: {
        display: 'flex',

        flexDirection: 'row',
        justifyContent: 'space-between'
    },
    bar: {
        height: 44,
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-between',
        borderTopWidth: 0.5,
        borderTopColor: '#d0d0d0'
    },
    barSummit: {
        backgroundColor: Color.primary,
        height: '100%',
        width: 104 / 375 * SCREEN.width,
    },
    noData: {
        display: 'flex',
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    loginBtn: {
        backgroundColor: Color.primary,
        width: 100,
        height: 30,
        borderRadius: 5,
        justifyContent: 'center',
        alignItems: 'center',
        marginTop: 10
    }


});
export default connect(
    ({auth, cart, mark}) => ({auth, cart, mark})
)(Page)



